package com.gpoint.rdp.web.context;

import java.util.Collection;
import java.util.Locale;


import org.slf4j.LoggerFactory;

import com.gpoint.rdp.api.base.cache.CacheKey;
import com.gpoint.rdp.api.base.cache.ICache;
import com.gpoint.rdp.api.base.cache.ICacheKeyGenerator;
import com.gpoint.rdp.api.base.constants.CacheKeyConstants;
import com.gpoint.rdp.api.base.context.CurrentContext;
import com.gpoint.rdp.api.base.model.PartyEntity;
import com.gpoint.rdp.api.base.model.User;

import com.gpoint.rdp.base.core.constants.StringPool;
import com.gpoint.rdp.base.core.util.AppUtil;
import com.gpoint.rdp.base.core.util.BeanUtils;
import com.gpoint.rdp.base.core.util.JacksonUtil;
import com.gpoint.rdp.base.core.util.string.StringUtil;
import com.gpoint.rdp.base.framework.persistence.entity.AbstractPo;
import com.gpoint.rdp.components.cache.CacheUtil;

/**
 * 获取登录信息。
 *
 * <pre> 
 * 构建组：ibps-platform-admin
 * 作者：hugh zhuang
 * 邮箱：3378340995@qq.com
 * 日期：2015-11-5-上午10:50:13
 * 版权：苏州东大金点物联科技有限公司版权所有
 * </pre>
 */
public class LoginContext implements  CurrentContext{
	
	/**
	 * 存放当前用户登录的语言环境
	 */
	private static ThreadLocal<Locale> currentLocale = new ThreadLocal<Locale>();
	/** * 当前上下文用户  */
	private static ThreadLocal<User> currentUser = new ThreadLocal<User>();
	/** * 当前上下文用户  */
	private static ThreadLocal<String> currentUserIp = new ThreadLocal<String>();
	/** * 当前上下文用户accessToken  */
	private static ThreadLocal<String> currentAccessToken = new ThreadLocal<String>();
	/** * 当前上下文用户组织  */
	private static ThreadLocal<PartyEntity> currentOrg = new ThreadLocal<PartyEntity>();
	/** * 当前上下文用户主岗位  */
	private static ThreadLocal<PartyEntity> currentPosition = new ThreadLocal<PartyEntity>();
	
	/**
	 * 获取当前语言环境
	 * @return
	 */
	public  Locale getLocale(){
		if(currentLocale.get()!=null){
			return currentLocale.get();
		}
		setLocale(new Locale("zh","CN"));
		return currentLocale.get();
	}
	
	/**
	 * 返回当前用户ID
	 * @return 
	 * String
	 * @exception 
	 * @since  1.0.0
	 */
	public  String getCurrentUserId(){
		User user=getCurrentUser();
		if(user==null) return null;
		return user.getUserId();
	}
	
	/**
	 * 返回当前用户accessToken
	 * @return 
	 * String
	 * @exception 
	 * @since  1.0.0
	 */
	public  String getCurrentAccessToken(){
		if(currentAccessToken.get()==null) return null;
		return currentAccessToken.get();
	}
	
	public  String getCurrentUserAccount(){
		User user=getCurrentUser();
		if(user==null) return null;
		return user.getAccount();
	}
	
	public  String getCurrentUserFullName(){
		User user=getCurrentUser();
		if(user==null) return null;
		return user.getFullname();
	}

	@SuppressWarnings("unchecked")
	public  User getCurrentUser() {
		if(currentUser.get()!=null){
			User user=currentUser.get();
			return user;
		}
		
		String username = null;
	/*	Subject subject = SecurityUtils.getSubject();
		PrincipalCollection pc = subject.getPrincipals();
		if(BeanUtils.isEmpty(pc)){
			LoggerFactory.getLogger(getClass()).warn("用户未登录或凭证丢失！");
			return null;
		}
		
		Collection<String> runC = pc.fromRealm(RealmConstants.RUN_REALM_NAME);
		while (runC.iterator().hasNext()) {
			username = runC.iterator().next();
			break;
		}*/
		
		// 从缓存中取
		ICache<?> iCache = (ICache<?>)AppUtil.getBean("iCache");
		ICacheKeyGenerator cacheKeyGenerator = AppUtil.getBean(ICacheKeyGenerator.class);
		CacheKey cacheKeyVo = cacheKeyGenerator.generate(CacheKeyConstants.CURRENT_USER + StringPool.COLON + username);
		String userKey = cacheKeyVo.getDefKey();
		if(iCache.containKey(userKey)) {
			return (User) iCache.getByKey(userKey);
		}
		
		return null;
	}
	
	@Override
	public PartyEntity getCurrentOrg() {
		if(currentOrg.get() != null){
			return currentOrg.get();
		}
		
		//从缓存中取
		ICache<?> iCache = (ICache<?>)AppUtil.getBean("iCache");
		ICacheKeyGenerator cacheKeyGenerator = AppUtil.getBean(ICacheKeyGenerator.class);
		CacheKey cacheKeyVo = cacheKeyGenerator.generate(CacheKeyConstants.CURRENT_ORG + StringPool.COLON + getCurrentUserAccount());
		String userKey = cacheKeyVo.getDefKey();
		if(iCache.containKey(userKey)) {
			return (PartyEntity) iCache.getByKey(userKey);
		}
		
		//获取当前人组织
		User user = getCurrentUser();
		if(BeanUtils.isEmpty(user)){
			return null;
		}
		
		return null;
	}
	
	/**
	 * 将当前组织放到线程变量和缓存中
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void setCurrentOrg(PartyEntity org) {
		currentOrg.set(org);
		if(BeanUtils.isEmpty(org)){
			return;
		}
		
		//将当前人和组织放到缓存中。
		ICache<PartyEntity> iCache=(ICache<PartyEntity>)AppUtil.getBean("iCache");
		ICacheKeyGenerator cacheKeyGenerator = AppUtil.getBean(ICacheKeyGenerator.class);
		CacheKey cacheKeyVo = cacheKeyGenerator.generate(CacheKeyConstants.CURRENT_ORG + StringPool.COLON + getCurrentUserAccount());
		String userKey=cacheKeyVo.getDefKey();
		int cacheExpire = CacheUtil.getExpire();
		iCache.add(userKey, org, cacheExpire);
	}
	
	/**清理线程中的用户变量，以及他的岗位信息*/
	public  void clearCurrentUser() {
		currentUser.remove();
		currentOrg.remove();
	}

	@SuppressWarnings("unchecked")
	public  void setCurrentUser(User user) {
		currentUser.set(user);
		if(BeanUtils.isEmpty(user)){
			return;
		}
		
		ICache<User> iCache=(ICache<User>)AppUtil.getBean("iCache");
		ICacheKeyGenerator cacheKeyGenerator = AppUtil.getBean(ICacheKeyGenerator.class);
		CacheKey cacheKeyVo = cacheKeyGenerator.generate(CacheKeyConstants.CURRENT_USER + StringPool.COLON + user.getAccount());
		String userKey=cacheKeyVo.getDefKey();
		int cacheExpire = CacheUtil.getExpire();
		iCache.add(userKey, user, cacheExpire);
	}

	public  void clearLocale() {
		currentLocale.remove();
	}

	public  void setLocale(Locale local) {
		currentLocale.set(local);
	}

	@Override
	public PartyEntity getCurrentPosition() {
		if(currentPosition.get()!=null){
			return currentPosition.get();
		}
		
		//从缓存中取
		ICache<?> iCache=(ICache<?>)AppUtil.getBean("iCache");
		ICacheKeyGenerator cacheKeyGenerator = AppUtil.getBean(ICacheKeyGenerator.class);
		CacheKey cacheKeyVo = cacheKeyGenerator.generate(CacheKeyConstants.CURRENT_POSITION + StringPool.COLON + getCurrentUserAccount());
		String userKey=cacheKeyVo.getDefKey();
		if(iCache.containKey(userKey)) {
			return (PartyEntity) iCache.getByKey(userKey);
		}
		
		//获取当前人的主岗位
		User user = getCurrentUser();
		if(BeanUtils.isEmpty(user)){
			return null;
		}
		return null;
	}

	@SuppressWarnings({ "unchecked" })
	@Override
	public void setCurrentPosition(PartyEntity position) {
		currentPosition.set(position);
		if(BeanUtils.isEmpty(position)){
			return;
		}
		
		//将当前人和组织放到缓存中
		ICache<PartyEntity> iCache=(ICache<PartyEntity>)AppUtil.getBean("iCache");
		ICacheKeyGenerator cacheKeyGenerator = AppUtil.getBean(ICacheKeyGenerator.class);
		CacheKey cacheKeyVo = cacheKeyGenerator.generate(CacheKeyConstants.CURRENT_POSITION + StringPool.COLON + getCurrentUserAccount());
		String userKey=cacheKeyVo.getDefKey();
		int cacheExpire = CacheUtil.getExpire();
		iCache.add(userKey, position, cacheExpire);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public String getCurrentUserIp() {
		if(currentUserIp.get()!=null){
			return currentUserIp.get();
		}
		
		if(BeanUtils.isNotEmpty(getCurrentUser())) {
			return ((AbstractPo<String>) getCurrentUser()).getIp();
		}
		
        return null;
	}

	@Override
	public void setCurrentUserIp(String ip) {
		currentUserIp.set(ip);
	}
	
	@Override
	public void setCurrentAccessToken(String accessToken) {
		currentAccessToken.set(accessToken);
	}

}
